package toOffer;

/**
 * <h3>leetcode</h3>
 *
 * @author BigFaceCat
 * @date 2024/1/28 15:09
 * @description <p>回文链表</p>
 */
public class toOffer4_4_27 {
    public static void main(String[] args) {
        int[] head = {1, 2, 3, 2, 1};
        ListNode node = new ListNode();
        ListNode newHead = node;
        for (int i = 0; i < head.length; i++) {
            node.val = head[i];
            if (i != head.length - 1) {
                node.next = new ListNode(head[i + 1]);
                node = node.next;
            } else {
                node.next = null;
            }
        }
        System.out.println(isPalindrome(newHead));
    }

    /**
     * 思路：
     * （1）找到链表的中间点，将链表分成两部分
     * （2）反转后半部分
     * （3）比较原前半部分与新后半部分之间的val值是否一样
     *
     * @param head
     * @return
     */
    public static boolean isPalindrome(ListNode head) {
        //初始化一个哨兵
        ListNode dummy = new ListNode();
        dummy.next = head;
        ListNode slow = dummy;
        ListNode fast = dummy;

        //找中间节点
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next;
            if (fast.next != null) {
                fast = fast.next;
            }
        }
        slow = reverseNode(slow);
        while (head!=null && slow != null){
            if (head.val != slow.val){
                return false;
            }
            head = head.next;
            slow = slow.next;
        }

        return true;
    }

    /**
     * 反转链表
     *
     * @param node
     * @return
     */
    public static ListNode reverseNode(ListNode node) {
        ListNode pre = null;
        ListNode curr = node;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
        }
        return pre;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

    }
}
